﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using Core.Message.Entities;
using Core.Controls.Message;
using Core.ExceptionHandling;
using vHCS.HR.Entities;
using vHCS.HR.Business;
using Core.Common.Session;

namespace vHCS.Web.MdlHR.Controls
{
    /// <summary>
    /// Tìm Kiếm Ứng Viên !
    /// </summary>
    public partial class HR_ctrUserSearch_App :Core.NTier.UserInterface.BaseUserControl
    {

        protected string trvOrgChartClientId;
        protected string trvProChartClientId;
        protected string trvMgtChartClientId;
        protected const string _REQ_REBIND_ACCOUNTNO = "RebindAccountNO";
        protected void Page_Load(object sender, EventArgs e)
        {
            this.GetTreeClientId();
        }

        #region Control Property

        /// <summary>
        /// Hiển thị nút chọn ứng viên
        /// </summary>
        public bool ChooseEmpInvisible
        {
            get { return this.btnChooseEmpCode.Visible; }
            set
            {
                this.btnChooseEmpCode.Visible = this.btnChooseEmpName.Visible=this.btnBarcode.Visible = value;
                if (value == false)
                {
                    Unit width = new Unit(100, UnitType.Percentage);
                    this.txtEmpCode.Width = this.txtEmpName.Width = width;
                }
            }
        }
        /// <summary>
        /// Giá trị các control
        /// </summary>
        public HR_UserSeachDTO_App ItemData
        {
            get
            {
                HR_UserSeachDTO_App controlData = new HR_UserSeachDTO_App();
                try
                {

                    controlData.EmployeeCode = this.EmpCode;
                    controlData.EmployeeName = this.EmpName;
                    controlData.Barcode = this.Barcode;
                    controlData.ReportToUserId = this.ReportTo;
                    controlData.Account = this.Usernames;
                    controlData.JobRoles = this.hdfJobRoles.Text.Trim();

                    controlData.ContractTypeId = this.ContractType;
                    controlData.EmployeeTypeId = this.EmpType;
                    controlData.OrgChartId = this.OrgChart;


                    controlData.ProRankingId = this.ProRanking;
                    controlData.ProGradeId = this.ProGrade;
                    //Cây cơ cấu chuyên môn
                    HIE_JobChartNode proSelected = this.ProJobChart;
                    controlData.ProJobFamilyId = proSelected.JobFamilyId;
                    controlData.ProJobGroupId = proSelected.JobGroupId;
                    controlData.ProSubGroupId = proSelected.SubGroupId;


                    controlData.MgtRankingId = this.MgtRanking;
                    controlData.MgtGradeId = this.MgtGrade;
                    //Cây cơ cấu chuyên môn
                    HIE_JobChartNode mgtSelected = this.MgtJobChart;
                    controlData.MgtJobFamilyId = mgtSelected.JobFamilyId;
                    controlData.MgtJobGroupId = mgtSelected.JobGroupId;
                    controlData.MgtSubGroupId = mgtSelected.SubGroupId;


                    controlData.JobTitleId = this.JobTitle;
                    controlData.JobLevelId = this.JobLevel;
                    controlData.WorkingLocationId = this.WorkingLocation;
                    controlData.TeminationStatus = this.TerminationStatus;

                }
                catch (Exception ex)
                {
                    AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                    MessageBox.Show(message);
                }
                return controlData;
            }
        }
        /// <summary>
        /// Mã ứng viên
        /// </summary>
        public string EmpCode
        {
            set { this.txtEmpCode.Text = value; }
            get { return this.txtEmpCode.Text.Trim(); }
        }
        /// <summary>
        /// Tên ứng viên
        /// </summary>
        public string EmpName
        {
            set { this.txtEmpName.Text = value; }
            get { return this.txtEmpName.Text.Trim(); }
        }
        /// <summary>
        /// Barcode
        /// </summary>
        public string Barcode
        {
            set { this.txtBarcode.Text = value; }
            get { return this.txtBarcode.Text.Trim(); }
        }
        /// <summary>
        /// Danh sách tên đăng nhập, cách nhau bởi dấu ;
        /// </summary>
        public string Usernames
        {
            set { this.txtUsernames.Text = value; }
            get { return this.txtUsernames.Text.Trim().Replace(" ", string.Empty); }
        }
        /// <summary>
        /// Account người báo cáo
        /// </summary>
        public string ReportTo
        {
            set { this.cboReportTo.SelectedValue = value; }
            get { return this.cboReportTo.SelectedValue.Trim(); }
        }
        /// <summary>
        /// Loại hợp đồng
        /// </summary>
        public long ContractType
        {
            set { this.cboContractType.SelectedValue = value.ToString(); }
            get
            {
                long lId = 0;
                long.TryParse(this.cboContractType.SelectedValue.Trim(), out lId);
                return lId;
            }
        }
        /// <summary>
        /// Loại ứng viên
        /// </summary>
        public long EmpType
        {
            set { this.cboEmpType.SelectedValue = value.ToString(); }
            get
            {
                long lId = 0;
                long.TryParse(this.cboEmpType.SelectedValue.Trim(), out lId);
                return lId;
            }
        }
        /// <summary>
        /// Cơ cấu tổ chức
        /// </summary>
        public long OrgChart
        {
            set
            {
                this.cboOrgChart.Items[0].Value = string.Empty;
                this.cboOrgChart.Items[0].Text = string.Empty;
                this.cboOrgChart.SelectedIndex = 0;
            }
            get
            {
                long lId = 0;
                long.TryParse(this.cboOrgChart.SelectedValue.Trim(), out lId);
                return lId;
            }
        }
        /// <summary>
        /// Raking theo cơ cấu nghề nghiệp
        /// </summary>
        public long ProRanking
        {
            set { this.cboProRanking.SelectedValue = value.ToString(); }
            get
            {
                long lId = 0;
                long.TryParse(this.cboProRanking.SelectedValue.Trim(), out lId);
                return lId;
            }
        }
        /// <summary>
        /// Grade theo cơ cấu nghề nghiệp
        /// </summary>
        public long ProGrade
        {
            set { this.cboProGrade.SelectedValue = value.ToString(); }
            get
            {
                long lId = 0;
                long.TryParse(this.cboProGrade.SelectedValue.Trim(), out lId);
                return lId;
            }
        }
        /// <summary>
        /// Cây cơ cấu nghề nghiệp
        /// </summary>
        public HIE_JobChartNode ProJobChart
        {
            set
            {
                this.cboProChart.Items[0].Value = string.Empty;
                this.cboProChart.Items[0].Text = string.Empty;
                this.cboProChart.SelectedIndex = 0;
            }
            get
            {
                return this.ParseNodeId(this.cboProChart.SelectedValue);
            }
        }

        /// <summary>
        /// Ranking theo cơ cấu quản lý
        /// </summary>
        public long MgtRanking
        {
            set { this.cboMgtRanking.SelectedValue = value.ToString(); }
            get
            {
                long lId = 0;
                long.TryParse(this.cboMgtRanking.SelectedValue.Trim(), out lId);
                return lId;
            }
        }
        /// <summary>
        /// Grade theo cơ cấu quản lý
        /// </summary>
        public long MgtGrade
        {
            set { this.cboMgtGrade.SelectedValue = value.ToString(); }
            get
            {
                long lId = 0;
                long.TryParse(this.cboMgtGrade.SelectedValue.Trim(), out lId);
                return lId;
            }
        }

        /// <summary>
        /// Cơ cấu quản lý
        /// </summary>
        public HIE_JobChartNode MgtJobChart
        {
            set
            {
                this.cboMgtChart.Items[0].Value = string.Empty;
                this.cboMgtChart.Items[0].Text = string.Empty;
                this.cboMgtChart.SelectedIndex = 0;
            }
            get
            {
                return this.ParseNodeId(this.cboMgtChart.SelectedValue);
            }
        }

        /// <summary>
        /// Chức vụ
        /// </summary>
        public long JobTitle
        {
            set { this.cboJobTitle.SelectedValue = value.ToString(); }
            get
            {
                long lId = 0;
                long.TryParse(this.cboJobTitle.SelectedValue.Trim(), out lId);
                return lId;
            }
        }
        /// <summary>
        /// Cấp bậc
        /// </summary>
        public long JobLevel
        {
            set { this.cboJobLevel.SelectedValue = value.ToString(); }
            get
            {
                long lId = 0;
                long.TryParse(this.cboJobLevel.SelectedValue.Trim(), out lId);
                return lId;
            }
        }
        /// <summary>
        /// Nơi làm việc
        /// </summary>
        public long WorkingLocation
        {
            set { this.cboWorkingLocation.SelectedValue = value.ToString(); }
            get
            {
                long lId = 0;
                long.TryParse(this.cboWorkingLocation.SelectedValue.Trim(), out lId);
                return lId;
            }
        }

        /// <summary>
        /// Tình trạng nghỉ việc
        /// </summary>
        public int TerminationStatus
        {
            set
            {
                this.rbtTerminationStatus.SelectedValue = ((int)value).ToString();
            }
            get
            {
                int status = int.Parse(this.rbtTerminationStatus.SelectedValue);
                return status;
            }
        }
        #endregion

        #region Proctected Helper Function


        /// <summary>
        /// Phân rã Id của node. 
        /// Cấu trúc Id của Node: JobFamilyId;JobGroupId;SubGroupId
        /// </summary>
        /// <param name="nodeId"></param>
        /// <returns></returns>
        protected HIE_JobChartNode ParseNodeId(string nodeId)
        {
            try
            {
                if (string.IsNullOrEmpty(nodeId)) return new HIE_JobChartNode();
                else if (nodeId.Trim() == "") return new HIE_JobChartNode();
                else
                {
                    string[] arrId = nodeId.Split(';');
                    if (arrId == null || arrId.Length < 3) return new HIE_JobChartNode();
                    HIE_JobChartNode node = new HIE_JobChartNode();
                    node.JobFamilyId = long.Parse(arrId[0].Trim());
                    node.JobGroupId = long.Parse(arrId[1].Trim());
                    node.SubGroupId = long.Parse(arrId[2].Trim());
                    return node;
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
            return new HIE_JobChartNode();

        }

        /// <summary>
        /// Load danh sách cho cboJobTitle
        /// </summary>
        protected void PopulateJobTitle()
        {
            try
            {
                long jobLevelId = 0;
                HIE_JobChartNode selectedNode = new HIE_JobChartNode();
                long.TryParse(cboJobLevel.SelectedValue, out jobLevelId);

                //Nếu cơ cấu quản lý không có giá trị thì chọn cơ cấu chuyên môn
                if (string.IsNullOrEmpty(cboMgtChart.SelectedValue)
                    || cboMgtChart.SelectedValue == HIE_HierarchyCollection.JobChartNullNodeValue)
                    selectedNode = this.ParseNodeId(cboProChart.SelectedValue);
                else
                    selectedNode = this.ParseNodeId(this.cboMgtChart.SelectedValue);

                dtsJobTitle.SelectParameters["jobLevelId"].DefaultValue = jobLevelId.ToString();
                dtsJobTitle.SelectParameters["jobFamilyId"].DefaultValue = selectedNode.JobFamilyId.ToString();
                dtsJobTitle.SelectParameters["jobGroupId"].DefaultValue = selectedNode.JobGroupId.ToString();
                dtsJobTitle.SelectParameters["subGroupId"].DefaultValue = selectedNode.SubGroupId.ToString();
                dtsJobTitle.CacheClear();
                cboJobTitle.DataBind();

            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// Lấy thông tin các treeview trong combo
        /// </summary>
        protected void GetTreeClientId()
        {
            try
            {
                Control ctrlOrgchart = this.cboOrgChart.Items[0].FindControl("trvOrgChart");
                trvOrgChartClientId = ctrlOrgchart.ClientID;
                Control ctrlProchart = this.cboProChart.Items[0].FindControl("trvProChart");
                trvProChartClientId = ctrlProchart.ClientID;
                Control ctrlMgtchart = this.cboMgtChart.Items[0].FindControl("trvMgtChart");
                trvMgtChartClientId = ctrlMgtchart.ClientID;
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        #endregion

        #region Public Function
        /// <summary>
        /// Xóa giá trị của tất cả control
        /// </summary>
        public void ResetForm()
        {
            try
            {
                this.txtBarcode.Text = string.Empty;
                this.txtEmpCode.Text = string.Empty;
                this.txtEmpName.Text = string.Empty;
                this.txtUsernames.Text = string.Empty;
                this.SetComboValue(this.cboContractType, string.Empty);
                this.SetComboValue(this.cboEmpType, string.Empty);
                this.SetComboValue(this.cboJobLevel, string.Empty);



                this.cboOrgChart.Items[0].Value = string.Empty;
                this.cboOrgChart.Items[0].Text = string.Empty;
                this.cboOrgChart.SelectedIndex = 0;


                this.cboMgtChart.Items[0].Value = string.Empty;
                this.cboMgtChart.Items[0].Text = string.Empty;
                this.cboMgtChart.SelectedIndex = 0;
                this.SetComboValue(this.cboMgtGrade, string.Empty);
                this.SetComboValue(this.cboMgtRanking, string.Empty);

                this.cboProChart.Items[0].Value = string.Empty;
                this.cboProChart.Items[0].Text = string.Empty;
                this.cboProChart.SelectedIndex = 0;

                this.SetComboValue(this.cboProGrade, string.Empty);
                this.SetComboValue(this.cboProRanking, string.Empty);
                this.SetComboValue(this.cboReportTo, string.Empty);
                this.SetComboValue(this.cboWorkingLocation, string.Empty);

                this.dtsJobTitle.CacheClear();
                this.SetComboValue(this.cboJobTitle, string.Empty);
                this.cboJobTitle.DataBind();
                this.ResetJobRole();

                this.rbtTerminationStatus.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        private void ResetJobRole()
        {
            foreach (RadComboBoxItem item in this.cboJobRole.Items)
            {
                CheckBox checkBox = (CheckBox)item.FindControl("chkJobRole");
                checkBox.Checked = false;
            }
            this.cboJobRole.SelectedValue = null;
            this.cboJobRole.Text = null;
            this.hdfJobRoles.Text = null;
        }

        #endregion

        #region Form Event

        /// <summary>
        /// Hàm xử lý sự kiện khi thay đổi giá trị của cấp bậc
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void cboJobLevel_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            PopulateJobTitle();
        }
        /// <summary>
        /// Hàm xử lý sự kiện click trên cây cơ cấu quản lý
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void trvMgtChart_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            this.PopulateJobTitle();
        }

        /// <summary>
        /// Hàm xử lý sự kiện click trên cây cơ cấu chuyên môn
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void trvProChart_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            //Nếu cơ cấu quản lý đã chọn, không lọc theo cơ cấu chuyên môn
            if (
                string.IsNullOrEmpty(cboMgtChart.SelectedValue) == true
                || cboMgtChart.SelectedValue == HIE_HierarchyCollection.JobChartNullNodeValue
                )
            {
                this.PopulateJobTitle();
            }
        }

        /// <summary>
        /// Sau khi thay đổi ứng viên
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EmployeeChanged(object sender, EventArgs e)
        {
            try
            {
                HR_EmpCollection collect = new HR_EmpCollection();
                HR_EmpCVCollection v_colEmpCV = new HR_EmpCVCollection();

                long lEmpId = 0;
                long.TryParse(this.hdfEmployeeId.Value, out lEmpId);
                HR_EmpDTO objEmp = collect.Get_EmpInfo_By_EmpID(lEmpId);
                HR_EmpCVDTO v_dtoEmpCV = v_colEmpCV.Get_EmpCV_By_EmpID(lEmpId);

                if (objEmp != null && v_dtoEmpCV != null)
                {
                    this.txtEmpCode.Text = objEmp.EmpCode;
                    this.txtEmpName.Text = v_dtoEmpCV.VLastName + " " + v_dtoEmpCV.VFirstName;
                    //this.txtBarcode.Text = objEmp.Barcode;
                }
                //Raise sự kiện thay đổi nhân viên
                if (this.SelectedEmployeeChanged != null)
                    this.SelectedEmployeeChanged(this, e);
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
        }
        #endregion

        #region Custom Event
        /// <summary>
        /// Raise sự kiện thay đổi nhân viên: Khi người dùng click nút ... chọn nhân viên
        /// </summary>
        public event System.EventHandler SelectedEmployeeChanged;
        #endregion
         /// <summary>
        /// Xử lý reload lại cbo chức vụ về trạng thái default 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ajxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            try
            {
                if (e.Argument.Equals(_REQ_REBIND_ACCOUNTNO))
                {


                    if (cboMgtChart.SelectedValue == "" && cboProChart.SelectedValue == "" && (cboJobLevel.SelectedValue == "" || cboJobLevel.SelectedValue == "0"))
                    {

                        dtsJobTitle.SelectParameters["jobLevelId"].DefaultValue = "0";
                        dtsJobTitle.SelectParameters["jobFamilyId"].DefaultValue = "0";
                        dtsJobTitle.SelectParameters["jobGroupId"].DefaultValue = "0";
                        dtsJobTitle.SelectParameters["subGroupId"].DefaultValue = "0";
                        dtsJobTitle.CacheClear();
                        cboJobTitle.DataBind();

                    }
                    else
                    {
                        this.PopulateJobTitle();
                    }
                    
                    
                }
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
        }
    }
}